﻿using Appliaction.IAppServices.Base_Manage;
using Domain.Entitys.Base_Manage;
using EFCore.Extention;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace Authoize.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class AuthoizeController : ControllerBase
    {
        private readonly IUserService userService;
        private readonly IRolesService rolesService;

        public AuthoizeController(IUserService userService, IRolesService rolesService)
        {
            this.userService = userService;
            this.rolesService = rolesService;
        }

        /// <summary>
        /// 登录生成token
        /// </summary>
        /// <param name="name">用户名</param>
        /// <param name="pwd">密码</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<JsonResult> Login(string name, string pwd)
        {
            pwd = MD5Helper.GetMD5Hash(pwd);//进行MD5加密
            Sys_User user = new Sys_User
            {
                User_account = name,
                User_pwd = pwd
            };
            Sys_User users = await userService.LoginAsync(user);
            if (users != null)
            {
                Sys_Role roles = await rolesService.GetRolesAsync(users.User_id);
                var claims = new List<Claim>();
                //{
                //    new Claim("user","admin")
                //};
                claims.Add(new Claim(ClaimTypes.Name, users.User_name));
                //claims.Add(new Claim(ClaimTypes.Role,"admin"));
                claims.Add(new Claim(ClaimTypes.Role, roles.Role_name));  // 默认角色

                //读取加密key-32个字符
                SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SDMC-CJAS1-SAD-DFSFA-SADHJVF-VFSS"));
                //指定加密算法
                SigningCredentials signingCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                JwtSecurityToken jwtSecurityToken = new JwtSecurityToken(
                    issuer: "http://localhost:5288",//颁发者
                    audience: "http://localhost:5181",//接受者
                    claims: claims,//自定义声明
                    expires: DateTime.Now.AddDays(1),//过期时间为一天
                    signingCredentials: signingCredentials//签名
                    );
                //生产token字符串
                var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
                //var cacheKey = $"JWT_{user.UserName}";

                //await distributedCache.SetStringAsync(
                //    cacheKey, token,
                //    new DistributedCacheEntryOptions
                //    {
                //        AbsoluteExpirationRelativeToNow = TimeSpan.FromDays(1)
                //    }
                //    );
                var respone = new
                {
                    Token = token,
                    RolesId = roles.Role_id,
                    UserId = users.User_id,
                    UserLName = users.User_name
                };

                return new JsonResult(respone);
            }
            else
            {
                return new JsonResult("账号或密码错误");
            }
        }
    }
}
